package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.fragments.LinkReciverFragment;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.BottomDialogOnclickListener;
import com.sxm.yiwei.utils.BottomDialogView;
import com.sxm.yiwei.utils.DialogUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OnceSendActivity extends BaseActivity implements View.OnClickListener{

    private ImageView onesendback;
    private ImageView oneimg1,oneimg2,oneimg3,oneimg4;
    private Button onetime1;
    private Button onetime2;
    private Button onetime3;
    private Button onetime4;
    private TextView oneleft;
    private TextView oneright;
    private TextView oneprice;
    private Button onecancel;
    private Button onesure;

    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final int PHOTO_TEXT = 3022;
    private static final int ADDRESSONE = 1001;
    /*用来标识请求gallery的activity*/
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private ArrayList<String> mList = new ArrayList<String>();
    private List<String>imglist = new ArrayList();
    private List<Object> imgId = new ArrayList<>();
    /*拍照的照片存储位置*/
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private File mCurrentPhotoFile;
    private Bitmap photo;
    // 按钮标志
    private int currentIndex;
    private int oneprice1;
    private Button add;
    private Button reduce;
    private TextView result;
    private int number;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    number = Integer.parseInt(String.valueOf(result.getText()));
                    onecMoneyText.setText(String.valueOf(number+10));
                    break;
            }
        }
    };
    private TextView onecMoneyText;
    private EditText inputExplain;
    private EditText inputprice;
    private Editable inprice;
    private RelativeLayout choosepossion;

    private String address1;
    private String phone1;
    private String name1;
    private EditText inpossion;
    private String path1;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private TextView pricemoney;
    private String possion;

    private String explain;
    private String price;
    private String money;
    private String id;
    private String password;
    private String isSetPassword;
    private String s;
    private AlertDialog dialog;
    private TextView oncex;
    private String amount;
    private ImageView oncepicbt;
    private LinearLayout imgs;
    private LinearLayout imgsline;
    private BaseIntents baseIntents;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_once_send);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initview();
        baseIntents = new BaseIntents();
        getContact();
    }
    //获取账户余额
    private void getAcountData() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/account/getAccountInfo");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                amount = obj1.getString("amount");
                Double nowmoney = Double.valueOf(amount);


                if (nowmoney<50.0){
                    AlertDialog.Builder builder = new AlertDialog.Builder(OnceSendActivity.this,R.style.NoBackGroundDialog);
                    View view = LayoutInflater.from(OnceSendActivity.this).inflate(R.layout.cancel_servicedialog,null);
                    Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                    Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                    TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                    builder.setView(view);
                    t2.setText("您的余额不足50元，请充值后发单");
                    final AlertDialog alertDialog = builder.create();
                    surebt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(OnceSendActivity.this,MineAccountJoinMoney.class));
                            alertDialog.dismiss();
                        }
                    });
                    cancelbt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                        }
                    });
                    alertDialog.show();
                }else {
                    getInData();
                    Double aDouble = Double.valueOf(price);
                    if (aDouble>=20.0){
                        if (explain.equals("")){
                            Toast.makeText(OnceSendActivity.this, "请输入您的简介", Toast.LENGTH_SHORT).show();
                        }else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(OnceSendActivity.this,R.style.NoBackGroundDialog);
                            View view = LayoutInflater.from(OnceSendActivity.this).inflate(R.layout.progress_dialog, null);
                            ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                            builder.setView(view);
                            dialog = builder.create();
                            dialog.show();
                            oneSendBook();
                        }

                    }else {
                        Toast.makeText(OnceSendActivity.this, "保价不得低于20元", Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    // 获取默认联系人
    private void getContact() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.ONE_CONTACTLINK);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("intro",explain);
        JSONObject object = new JSONObject();
        //类型0：发件人 类型1:收件人
        object.put("type","0");
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                JSONObject obj1 = JSON.parseObject(data);
                String address = obj1.getString("address");
                id = obj1.getString("id");
                inpossion.setText(address);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initview() {
        // 返回上一页
        onesendback = (ImageView) findViewById(R.id.oneseng_back);
        // 商品图片
        oneimg1 = (ImageView) findViewById(R.id.onesend_img1);
        oneimg2 = (ImageView) findViewById(R.id.onesend_img2);
        oneimg3 = (ImageView) findViewById(R.id.onesend_img3);

        inputExplain = (EditText) findViewById(R.id.onesend_inputexplain);
        inputprice = (EditText) findViewById(R.id.onesend_inputprice);
        inpossion = (EditText) findViewById(R.id.onesend_inpossion);
        choosepossion = (RelativeLayout) findViewById(R.id.oncesend_chosepossion);
        pricemoney = (TextView) findViewById(R.id.once_moneytext);
        oncex = (TextView) findViewById(R.id.once_x);
        oncepicbt = (ImageView) findViewById(R.id.once_picbt);
        imgs = (LinearLayout) findViewById(R.id.once_imgs);
        imgsline = (LinearLayout) findViewById(R.id.once_imgsline);
        // 设置光标的位置

        add = (Button) findViewById(R.id.add);
        reduce = (Button) findViewById(R.id.reduce);
        result = (TextView) findViewById(R.id.t_result);
        onecMoneyText = (TextView) findViewById(R.id.once_moneytext);

        // 取消订单提交订单

        onesure = (Button) findViewById(R.id.one_sure);
        backmain = (ImageView) findViewById(R.id.once_backmain);
        backmain.setOnClickListener(this);
        choosepossion.setOnClickListener(this);
        onesendback.setOnClickListener(this);
        oncex.setOnClickListener(this);
        add.setOnClickListener(this);
        reduce.setOnClickListener(this);
        oneimg1.setOnClickListener(this);
        oneimg2.setOnClickListener(this);
        oneimg3.setOnClickListener(this);
        onesure.setOnClickListener(this);
        oncepicbt.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.once_backmain:
                startActivity(new Intent(OnceSendActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.once_picbt:
                imgs.setVisibility(View.VISIBLE);
                imgsline.setVisibility(View.VISIBLE);
                break;
            case R.id.once_x:
                Intent i = new Intent(OnceSendActivity.this,WEBXActivity.class);
                i.putExtra("from","hot");
                i.putExtra("url", InternetAddressUtis.XNOSEND);
                startActivity(i);
                break;
            case R.id.one_sure:
              // 提交订单数据
                getAcountData();
                break;
            case R.id.oneseng_back:
                finish();
                break;
            case R.id.onesend_img1:
                doPickPhotoAction();
                currentIndex=1;
                break;
            case R.id.onesend_img2:
                doPickPhotoAction();
                currentIndex=2;
                break;
            case R.id.onesend_img3:
                doPickPhotoAction();
                currentIndex=3;
                break;

            case R.id.add:
                int aNumber = Integer.parseInt(String.valueOf(result.getText()));
                    aNumber++;
                    result.setText(String.valueOf(aNumber));
                handler.sendEmptyMessage(1);
                result.setText(String.valueOf(aNumber));
                break;
            case R.id.reduce:
                int rNumber = Integer.parseInt(String.valueOf(result.getText()));
                    if (rNumber>0){
                        rNumber--;
                         handler.sendEmptyMessage(1);
                        result.setText(String.valueOf(rNumber));
                    }else{
                        Toast.makeText(this, "对不起,此商品暂无优惠,如有优惠我们会通知您", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.oncesend_chosepossion:

                Intent in = new Intent(OnceSendActivity.this, MineServicer.class);
                in.putExtra("from","1");
                startActivityForResult(in,ADDRESSONE);
                break;

        }
    }
        // 发送订单
    private void oneSendBook() {
        // 获取客户输入信息
        getInData();
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.ONE_SEND);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("intro",explain);
        params.addBodyParameter("consignorId",id);
        Log.d("tag", "oneSendBook: id--->"+id);
        params.addBodyParameter("insurance",price);
        params.addBodyParameter("total_amount",s);
        for (int i = 0; i < imglist.size(); i++) {

            params.addBodyParameter("order",new File(imglist.get(i)));

        }

        params.setMultipart(true);


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                com.alibaba.fastjson.JSONObject obj2 = JSON.parseObject(result);
                String data = obj2.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                final String orderId = obj1.getString("orderId");
                // 判断是否设置支付密码
                RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.PAYWORDSTATES);
                params.setHeader("Content-Type","application/json");
                params.setHeader("token", token);
                params.setHeader("appId", appId);
                params.setHeader("userId", userId);
                x.http().get(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject object = JSON.parseObject(result);
                        String data = object.getString("data");
                        JSONObject object1 = JSON.parseObject(data);
                        isSetPassword = object1.getString("isSetPassword");
                        if (isSetPassword.equals("true")){
                            // 订单发送成功 调用支付接口
                            showDialog(orderId);
                        }else {
                            Toast.makeText(OnceSendActivity.this, "请设置支付密码", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(OnceSendActivity.this,MinePayPasswordActivity.class));
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {


            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    // 支付  输入支付密码
    private void showDialog(final String s) {
        DialogUtil.showBottomDialog(OnceSendActivity.this, R.id.once_send_window, new BottomDialogOnclickListener() {
            @Override
            public void onPositiveClick(String contentStr, BottomDialogView dialogView) {
                payBook(s,contentStr);
                // 点击后消失
                dialogView.dismiss();
            }
        });
    }
        // 支付订单 只能余额支付
    private void payBook(String s,String word) {
            getInData();

       Double dPrice = Double.valueOf(price)*0.05;
        final Double dMoney = Double.valueOf(money)+dPrice;


        try {
            password = AESUtil.encryptAES(word);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams p = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.ONE_SENDPAY);
        p.addHeader("Content-Type","application/json");
        p.addHeader("token",token);
        p.addHeader("appId",appId);
        p.addHeader("userId",userId);

        JSONObject j = new JSONObject();
        j.put("payOrderType","05");
        j.put("payPassword",password);
        j.put("orderId",s);
        j.put("total_amount",String.valueOf(dMoney));
        p.setBodyContent(j.toJSONString());
        x.http().post(p, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject object = JSON.parseObject(result);
                String status = object.getString("status");
                if (status.equals("1")){
                    AlertDialog.Builder b = new AlertDialog.Builder(OnceSendActivity.this,R.style.NoBackGroundDialog);
                    b.setTitle("支付结果");
                    b.setMessage("您已成功支付:"+dMoney+" 元");
                    b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                    b.create().show();
                }else {
                    String failure = object.getString("failure");
                    if (failure.equals("1016")){
                        AlertDialog.Builder builder = new AlertDialog.Builder(OnceSendActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(OnceSendActivity.this).inflate(R.layout.cancel_servicedialog, null);
                        builder.setView(view);
                        Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                        Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                        TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                        t2.setText("余额不足，请充值");
                        final AlertDialog dialog = builder.create();
                        cancelbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        surebt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(OnceSendActivity.this,MineAccountJoinMoney.class));
                                dialog.dismiss();
                            }
                        });
                        dialog.show();

                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: ex---pay-->"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    // 获取客户输入信息
    private void getInData() {
        possion = String.valueOf(inpossion.getText());  // 发货人
        explain = String.valueOf(inputExplain.getText());// 订单简介
        price = String.valueOf(inputprice.getText()); //保价
        money = String.valueOf(pricemoney.getText()); // 总价
        if (price.equals("")){
           s= money;
            price="0";
        }else {
            Double d = Double.valueOf(price)*0.05;
            Double m = Double.valueOf(money);
            Double mPrice = d+m;
            s = String.valueOf(mPrice);
        }

    }
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);

    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的


                photo = data.getParcelableExtra("data");

                String s = CropPictures.saveBitmapFile(photo, new BaseIntents().getPhotoFileName());

                imglist.add(s);
                switch (imglist.size()){
                    case 0:
                        break;
                    case 1:
                        oneimg2.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        oneimg3.setVisibility(View.VISIBLE);
                        break;
                }

                if (currentIndex==1){
                    oneimg1.setImageBitmap(photo);
                }else if (currentIndex==2){
                    oneimg2.setImageBitmap(photo);
                }else if (currentIndex==3){
                    oneimg3.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;
            case ADDRESSONE:
                    // 获取联系人 返回的数据
                Bundle ab = data.getExtras();
                String address1 = String.valueOf(ab.get("address1"));
                id = String.valueOf(ab.get("id"));
                inpossion.setText(address1);
                break;


        }


    }


}
